﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LeastSquares.LeastSquaresMethod
{
    internal class Models
    {
        /// <summary>
        /// 回归方程
        /// </summary>
        /// <param name="yearList"></param>
        /// <param name="GDPList"></param>
        /// <param name="y"></param>
        /// <param name="x"></param>
        /// <returns></returns>
        public static double LeastSquaresMethod(List<int> yearList, List<double> GDPList, double y, double x)
        {
            //建立平均值点坐标(avex,avey)
            double avex = 0;
            double avey = 0;
            //创建x的和 y的和
            double sumx = 0;
            double sumy = 0;
            //创建分子numerator和分母denominator
            double numerator = 0;
            double denominator = 0;
            //创建a和b
            double a = 0;
            double b = 0;
            //计算avex,avey
            for (int i = 0; i < yearList.Count; i++)
            {
                sumx += yearList[i];
                sumy += GDPList[i];
            }
            avex = sumx / yearList.Count;
            avey = sumy / GDPList.Count;
            //代入公式计算a和b           
            for (int i = 0; i < yearList.Count; i++)
            {
                numerator += (yearList[i] - avex) * (GDPList[i] - avey);
                denominator += (yearList[i] - avex) * (yearList[i] - avex);
            }
            b = numerator / denominator;
            a = avey - b * avex;
            //得到拟合函数y=a+bx           
            y = a + b * x;
            return y;
        }
    }
}
